from ais.core import *
import time
import sys
import os
import math
import logging
from pathlib import Path
import torch
import numpy as np

from ais.utils import cfg, load_cfg_file, set_random_seed, get_state_dict, setup_logger, print_torch_version, logger_addHandler
from ais.image import cv_show, cv_keyboard_run, cv_resize_shape, convert_mask_to_image, cv_imread, \
    SkullTemplateMatch, cv_cvtcolor, segment_largest_roi_from_image, is_image_file, is_dcm_file, read_dcm_to_8bit, \
    remove_small_objects, find_bounding_rect, draw_vetebra_landmarks
from ais.cobb import calculate_cobb, calculate_kps_angles
from ais.model import SpineNet, SegHighResolutionNet

from ais.infer import BaseInfer
from app.keypoint_infer import KeypointInfer
from app.seg_infer import SegInfer

lat = []
class DRCobbDet(object):
    def __init__(self, logger_file):
        """
        cobb角检测类
        :param logger_file:
        """
        self.logger = setup_logger(Path(__file__).name, level=logging.INFO, filepath=logger_file)
        self.skull_matcher = None                # 头骨匹配实例
        self.vertebra_dr_seger: BaseInfer = None # spine分割实例
        self.vertebra_dr_kp: BaseInfer = None    # spine关键点检测实例

    def init(self):
        """
        初始化模型以及相关预处理工具
        :return:
        """

        try:
            logger_file = self.logger.handlers[1].baseFilename
        except Exception as e:
            self.logger.error("get logger_file error: {}".format(e))
            logger_file = Path(cfg.LOG.DIR).joinpath("AIS-WebServer" + time.strftime("--%Y-%m-%d-%H-%M-%S", time.localtime()))

        # 1 spine关键点模型定义
        kp_model = eval(cfg.MODEL.LANDMARK_DET.MODEL)(cfg.MODEL.LANDMARK_DET.CHANNELS,
                            cfg.MODEL.LANDMARK_DET.KP_NUM,
                            **cfg.MODEL.LANDMARK_DET.MODEL_PARAMETER)

        device = self.get_device(cfg.MODEL.LANDMARK_DET.DEVICE)
        # 初始化spine关键点检测实例
        self.vertebra_dr_kp = KeypointInfer(kp_model,
                                            device,
                                            cfg.NUM_GPUS,
                                            cfg.MODEL.LANDMARK_DET.SHAPE,
                                            down_ratio=4)
        # 加载spine关键点检测模型
        self.vertebra_dr_kp.init(cfg.MODEL.LANDMARK_DET.PRETRAINED, str(logger_file))

        # 2 spine分割模型定义
        seg_model = eval(cfg.MODEL.SEMANTIC_SEG.MODEL)(cfg.MODEL.SEMANTIC_SEG.CHANNELS,
                                         cfg.MODEL.SEMANTIC_SEG.NUM_CLASSES,
                                         **cfg.MODEL.SEMANTIC_SEG.MODEL_PARAMETER)
        device = self.get_device(cfg.MODEL.SEMANTIC_SEG.DEVICE)

        # 初始化spine分割实例
        self.vertebra_dr_seger = SegInfer(seg_model,
                                          device,
                                          cfg.NUM_GPUS,
                                          cfg.MODEL.SEMANTIC_SEG.SHAPE,
                                          cfg.MODEL.SEMANTIC_SEG.STATS)
        # 加载spine分割模型
        self.vertebra_dr_seger.init(cfg.MODEL.SEMANTIC_SEG.PRETRAINED, str(logger_file))

        # 初始化头骨匹配实例
        if Path(cfg.INFER.PRE_PROCESS.SKULL_TEMPLATE).exists():
            template = cv_imread(str(cfg.INFER.PRE_PROCESS.SKULL_TEMPLATE), 0)
            if template is not None:
                self.skull_matcher = SkullTemplateMatch(template, method=4)
            else:
                self.logger.info("image: app/template/skull.bmp read failed")

    def get_device(self, device_desc):
        """
        根据device_desc获取torch device
        :param device_desc:
        :return:
        """
        if torch.cuda.is_available() and 'cuda' in device_desc:
            device = torch.device('cuda:0')
            if len(str(device_desc).split(':')) > 1:
                device_id = int(str(device_desc).split(':')[-1])
                if device_id < torch.cuda.device_count():
                    device = torch.device('cuda:'+str(device_id))
        else:
            device = torch.device('cpu')
        return device

    def pre_process(self, image: NPImage):
        """
        1.截取目标前景crop object foreground
        2.移除头骨remove skull
        :param image:
        :return:
        """
        COLOR_BGR2GRAY = 6
        gray_image = cv_cvtcolor(image, COLOR_BGR2GRAY)
        # 1.crop roi
        min_x, min_y, max_x, max_y = segment_largest_roi_from_image(gray_image, debug=cfg.DEBUG)

        # 2.remove skull
        if self.skull_matcher is not None:
            skull_rect, skull_exist = self.skull_matcher.match_image(gray_image[min_y:max_y, min_x:max_x])
            if skull_exist:
                offset_h = skull_rect[1][1]
                crop_image = image[min_y + offset_h:max_y, min_x:max_x]
                return {'xyxy': (min_x, min_y + offset_h, max_x, max_y),
                        'input_shape': image.shape[:2],
                        'output_shape': crop_image.shape[:2]}, crop_image

        crop_image = image[min_y:max_y, min_x:max_x]
        return {'xyxy': (min_x, min_y, max_x, max_y),
                'input_shape': image.shape[:2],
                'output_shape': crop_image.shape[:2]}, crop_image

    def post_process(self, reg_kp, crop_dict, bounding_xyxy_dict):
        """
        将最后的识别结果映射到原始输入图像的尺寸上
        """
        reg_kp[:, 0] += bounding_xyxy_dict['xyxy'][0]
        reg_kp[:, 1] += bounding_xyxy_dict['xyxy'][1]
        reg_kp[:, 0] = np.clip(reg_kp[:, 0], 0, bounding_xyxy_dict['input_shape'][1] - 1)
        reg_kp[:, 1] = np.clip(reg_kp[:, 1], 0, bounding_xyxy_dict['input_shape'][0] - 1)

        # seg_landmark resize to crop_dict
        if crop_dict:
            crop_landmark = np.copy(reg_kp)
            crop_landmark[:, 0] += crop_dict['xyxy'][0]
            crop_landmark[:, 1] += crop_dict['xyxy'][1]
            crop_landmark[:, 0] = np.clip(crop_landmark[:, 0], 0, crop_dict['input_shape'][1] - 1)
            crop_landmark[:, 1] = np.clip(crop_landmark[:, 1], 0, crop_dict['input_shape'][0] - 1)
            return crop_landmark.astype(np.int)
        else:
            return reg_kp.astype(np.int)

    def get_bounding_box(self, mask:NPImage, offset=30):
        """
        计算二值图像最大的bounding box
        :param mask:
        :param offset:
        :return:
        """
        bounding_xyxy, _ = find_bounding_rect(mask * 255)
        bounding_xyxy[0] -= offset
        bounding_xyxy[1] -= offset
        bounding_xyxy[2] += offset
        bounding_xyxy[3] += offset
        h, w = mask.shape[0], mask.shape[1]
        bounding_xyxy[0::2] = np.clip(bounding_xyxy[0::2], 0, w)
        bounding_xyxy[1::2] = np.clip(bounding_xyxy[1::2], 0, h)
        return bounding_xyxy

    @property
    def spine_indexs(slef):
        """
        每块椎体的索引
        """
        return ('T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10', 'T11', 'T12', 'L1', 'L2', 'L3', 'L4', 'L5')

    def calculate_ap_cobb(self, kp):
        """
        对输入的68个关键点计算cobb角，以及对应的上下终板索引和对应的cobb角边界线
        :param kp: keypoints shape [68, 2]
        :return:
                bend_angles: {'pt': {'angle':30, 'line_index': [5, 10],
                              'up_endplate':'T5', 'down_endplate': T12,
                              'up_line':{'start_x':10, 'start_y': 200, 'end_x': 60, 'end_y': 200},
                              'down_line':{'start_x':100, 'start_y': 500, 'end_x': 600, 'end_y': 700} },
                              'mt':{...}, 'tl':{...}}
        """
        angles, peaks, valleys, bend_angles = calculate_cobb(kp)

        for k in bend_angles.keys():
            line_index = bend_angles[k]['line_index']

            assert len(line_index) == 2
            line_index.sort()

            for i, id in enumerate(line_index):
                # spine_tuple.append((id+1)//2 + (id+1)%2)
                # lines.append([kp[id * 2].tolist(), kp[id * 2 + 1].tolist()])
                spine_idx = (id+1)//2 + (id+1)%2
                spine_desc = self.spine_indexs[spine_idx-1]
                s1 = kp[id * 2].tolist()
                s2 = kp[id * 2 + 1].tolist()
                pt = {'start_x':s1[0], 'start_y': s1[1], 'end_x': s2[0], 'end_y': s2[1]}

                if i == 0:
                    bend_angles[k]['up_endplate'] = spine_desc
                    bend_angles[k]['up_line'] = pt
                else:
                    bend_angles[k]['down_endplate'] = spine_desc
                    bend_angles[k]['down_line'] = pt
        # extend lines
        self.extend_cobb_lines(bend_angles)
        return bend_angles, kp

    def extend_cobb_lines(self, bend_angles:dict):
        """
        将cobb角的边界线延伸
        :param bend_angles: bend_angles: {'pt': {'angle':30, 'line_index': [5, 10],
                              'up_endplate':'T5', 'down_endplate': T12,
                              'up_line':{'start_x':10, 'start_y': 200, 'end_x': 60, 'end_y': 200},
                              'down_line':{'start_x':100, 'start_y': 500, 'end_x': 600, 'end_y': 700} },
                              'mt':{...}, 'tl':{...}}
        :return:
        """

        def __extend_line(vertbra_line:dict):
            k = (vertbra_line['end_y'] - vertbra_line['start_y']) / (vertbra_line['end_x'] - vertbra_line['start_x'])
            b = vertbra_line['start_y'] - k * vertbra_line['start_x']
            vertebra_offset = math.sqrt(math.pow((vertbra_line['end_y'] - vertbra_line['start_y']), 2) + math.pow(
                (vertbra_line['end_x'] - vertbra_line['start_x']), 2))

            x0 = int(vertbra_line['start_x'] - math.sqrt((4 * math.pow(vertebra_offset, 2) / (1 + math.pow(k, 2)))))
            vertbra_line['start_y'] = int(k * (x0 - vertbra_line['start_x']) + vertbra_line['start_y'])
            vertbra_line['start_x'] = x0

            x0 = int(vertbra_line['end_x'] + math.sqrt((4 * math.pow(vertebra_offset, 2) / (1 + math.pow(k, 2)))))
            vertbra_line['end_y'] = int(k * (x0 - vertbra_line['end_x']) + vertbra_line['end_y'])
            vertbra_line['end_x'] = x0

        for k, v in bend_angles.items():
            __extend_line(v['up_line'])
            __extend_line(v['down_line'])

    def calculate_bend_cobb(self, kp, ap_dict:dict):
        """
        使用AP位cobb信息, 计算bending位的cobb角
        :param kp:keypoints
        :param ap_dict:
        ap_dict: {'pt': {'angle':30, 'line_index': [5, 10],
                              'up_endplate':'T5', 'down_endplate': T12,
                              'up_line':{'start_x':10, 'start_y': 200, 'end_x': 60, 'end_y': 200},
                              'down_line':{'start_x':100, 'start_y': 500, 'end_x': 600, 'end_y': 700} },
                              'mt':{...}, 'tl':{...}}
        :return:
        """

        thoracic_index = {'PT': (0, 5), 'MT': (6, 12), 'TL/L': (13, 17)}
        # 1.计算夹角
        bend_dict = {}
        angles = calculate_kps_angles(kp)
        for k, v in ap_dict.items():
            bend_dict[k]= {}
            line_index = v['line_index']
            assert len(line_index) == 2
            line_index.sort()
            bend_dict[k]['angle'] = round(abs(angles[int(line_index[0])] - angles[int(line_index[1])]), 2)
            bend_dict[k]['line_index'] = v['line_index']
            bend_dict[k]['up_endplate'] = v['up_endplate']
            bend_dict[k]['down_endplate'] = v['down_endplate']
            up_left = (kp[line_index[0] * 2]).astype(int)
            up_right = (kp[line_index[0] * 2 + 1]).astype(int)
            bend_dict[k]['up_line'] = {'start_x':up_left[0], 'start_y': up_left[1], 'end_x': up_right[0], 'end_y': up_right[1]}
            down_left = (kp[line_index[1] * 2]).astype(int)
            down_right = (kp[line_index[1] * 2 + 1]).astype(int)
            bend_dict[k]['down_line'] = {'start_x': down_left[0], 'start_y': down_left[1], 'end_x': down_right[0], 'end_y': down_right[1]}

        # extend lines
        self.extend_cobb_lines(bend_dict)
        return bend_dict

    def vertical_line(self, x1, y1, x2, y2):
        """
        计算vertical line
        :param x1:
        :param x2:
        :param y1:
        :param y2:
        :return:
        """
        a = (x1 - x2)/(y2 - y1)
        x = x1 - a * (400/(a**2+1))**0.5
        y = y1 - a * (400/(a**2+1))**0.5
        if x > x1:
            x = x1 + a * (400 / (a ** 2 + 1)) ** 0.5
            y = y1 + a * (400 / (a ** 2 + 1)) ** 0.5
        return int(x), int(y)

    def get_angle(self, v1, v2):
        """
        计算两条线段之间的夹角
        :param line1:
        :param line2:
        :return:
        """
        dx1 = v1[2] - v1[0]
        dy1 = v1[3] - v1[1]
        dx2 = v2[2] - v2[0]
        dy2 = v2[3] - v2[1]
        angle1 = math.atan2(dy1, dx1)
        angle1 = round(float(angle1 * 180 / math.pi) ,2)
        # print(angle1)
        angle2 = math.atan2(dy2, dx2)
        angle2 = round(float(angle2 * 180 / math.pi) ,2)
        # print(angle2)
        if angle1 * angle2 >= 0:
            included_angle = abs(angle1 - angle2)
        else:
            included_angle = abs(angle1) + abs(angle2)
            if included_angle > 180:
                included_angle = 360 - included_angle
        return included_angle

    def calculate_lat_cobb(self, kp):
        """
        使用lat位cobb信息, 计算lat位的cobb角
        :param kp:keypoints
        lat_dict: {'pt': {'angle':30,
                          'up_endplate':'T5', 'down_endplate': T12,
                          'up_line':{'start_x':10, 'start_y': 200, 'end_x': 60, 'end_y': 200},
                          'down_line':{'start_x':100, 'start_y': 500, 'end_x': 600, 'end_y': 700} },}
        :return:
        """
        thoracic_index = {'PT': (0, 5), 'MT': (6, 12), 'TL/L': (13, 17)}
        # 1.计算夹角
        lat_dict = {}
        lat_dict['PT'] = {}
        # 将kp16，18和44，46点从ap坐标系转换到lat坐标系下
        # lat_point16 = self.kp_convert(kp[16])
        # 计算 start point
        T5x, T5y = self.vertical_line(kp[16][0], kp[16][1], kp[18][0], kp[18][1])
        T12x, T12y = self.vertical_line(kp[44][0], kp[44][1], kp[46][0], kp[46][1])
        L1 = [T5x, T5y, kp[16][0], kp[16][1]]
        L2 = [T12x, T12y, kp[46][0], kp[46][1]]
        lat_dict['PT']['angle'] = self.get_angle(L1, L2)
        lat_dict['PT']['line_index'] = [5, 12]
        lat_dict['PT']['up_endplate'] = 'T5'
        lat_dict['PT']['down_endplate'] = 'T12'
        lat_dict['PT']['up_line'] = {'start_x': T5x, 'start_y': T5y, 'end_x': kp[16][0], 'end_y': kp[16][1]}
        lat_dict['PT']['down_line'] = {'start_x': T12x, 'start_y': T12y, 'end_x': kp[46][0], 'end_y': kp[46][1]}

        # extend lines
        self.extend_cobb_lines(lat_dict)
        return lat_dict

    def process(self, image_or_path, orientation='AP', lat_kp=None, **kwargs):
        """
        cobb角检测算法流程
        :param image_file:
        :return:
                orientation: AP  LAT LBend RBend
                bend_angles: {'pt': {'angle':30, 'line_index': [5, 10],
                              'up_endplate':'T5', 'down_endplate': T12,
                              'up_line':{'start_x':10, 'start_y': 200, 'end_x': 60, 'end_y': 200},
                              'down_line':{'start_x':100, 'start_y': 500, 'end_x': 600, 'end_y': 700} },
                              'mt':{...}, 'tl':{...}}


        """
        # cfg.DEBUG = True
        # 1. read image
        if isinstance(image_or_path, NPArray):
            org_image = image_or_path
        elif isinstance(image_or_path, Path) or isinstance(str(image_or_path), str):
            if not Path(image_or_path).exists():
                self.logger.info(__name__ + " process input: {} file not exist!".format(str(image_or_path)))
                return None
            try:
                if is_dcm_file(str(image_or_path)):
                    org_image = read_dcm_to_8bit(str(image_or_path))
                    org_image = np.repeat(org_image[..., np.newaxis], 3, 2)
                elif is_image_file(str(image_or_path)):
                    org_image = cv_imread(str(image_or_path), 1)
            except Exception as e:
                self.logger.error(__name__ + " process input: {} file not exist!".format(str(image_or_path)))
                return None

        # 2.crop image
        if cfg.DATA_LOADER.CROP:
            crop_dict, crop_image = self.pre_process(org_image)
        else:
            crop_image = org_image
            crop_dict = None

        if cfg.DEBUG:
            cv_show('crop_image', crop_image, resize=0.7)
            cv_keyboard_run()

        # 3.1 segement vertebra
        vertebra_mask = self.vertebra_dr_seger.process(crop_image)

        # 3.1.1 对二值图像进行后处理
        vertebra_mask = remove_small_objects(vertebra_mask * 255)
        if cfg.DEBUG:
            cv_show('vertebra_seg_map', vertebra_mask*255, resize=1.0)
            cv_keyboard_run()

        bounding_xyxy = self.get_bounding_box(vertebra_mask)
        bounding_xyxy_dict = {'xyxy':bounding_xyxy,
                              'input_shape': vertebra_mask.shape[:2]}

        # 3.1.2 crop vertebra image
        # by bounding_box
        vertebra_seg_image = crop_image[bounding_xyxy[1]: bounding_xyxy[3], bounding_xyxy[0]: bounding_xyxy[2]]
        if cfg.DEBUG:
            cv_show('vertebra_seg_image', vertebra_seg_image, resize=1.0)
            cv_keyboard_run()

        # 3.2 kp detection
        vertebra_kp = self.vertebra_dr_kp.process(vertebra_seg_image)

        if cfg.DEBUG:
            show_image = np.copy(vertebra_seg_image)
            draw_vetebra_landmarks(vertebra_kp, show_image)
            cv_show('show_crop_image_landmark', show_image, resize=1.0)
            cv_keyboard_run()

        # 3.3 关键点坐标后处理
        vertebra_kp = self.post_process(vertebra_kp, crop_dict, bounding_xyxy_dict)
        # 3.4 计算cobb角信息
        if orientation == 'AP':
            return self.calculate_ap_cobb(vertebra_kp)
        elif orientation == 'LBend' or orientation == 'RBend':
            return self.calculate_bend_cobb(vertebra_kp, kwargs['ap_dict'])
        elif orientation == 'LAT':
            return self.calculate_lat_cobb(lat_kp)

    def evaluate_case(self, image_or_path, orientation='AP', **kwargs):
        """cobb角测量本地测试评估"""
        import cv2

        # cobb_dict: {'pt': {'angle': 30, 'line_index': [5, 10],
        #                      'up_endplate': 'T5', 'down_endplate': T12,
        #                      'up_line': {'start_x': 10, 'start_y': 200, 'end_x': 60, 'end_y': 200},
        #                      'down_line': {'start_x': 100, 'start_y': 500, 'end_x': 600, 'end_y': 700}},
        #               'mt': {...}, 'tl': {...}}
        cobb_dict, kp = self.process(image_or_path)

        if isinstance(image_or_path, NPArray):
            show_pred_image = image_or_path
        elif isinstance(image_or_path, Path) or isinstance(str(image_or_path), str):
            if not Path(image_or_path).exists():
                self.logger.info(__name__ + " process input: {} file not exist!".format(str(image_or_path)))
                return None
            try:
                if is_dcm_file(str(image_or_path)):
                    show_pred_image = read_dcm_to_8bit(str(image_or_path))
                    show_pred_image = np.repeat(show_pred_image[..., np.newaxis], 3, 2)
                elif is_image_file(str(image_or_path)):
                    show_pred_image = cv_imread(str(image_or_path), 1)
            except Exception as e:
                self.logger.error(__name__ + " process input: {} file not exist!".format(str(image_or_path)))
                return None

        for i, pt in enumerate(kp):
            show_pred_image = cv2.circle(show_pred_image, (int(pt[0]), int(pt[1])), 2, (0, 255, 0), 2)

        for k, v in cobb_dict.items():
            cv2.circle(show_pred_image, (v['up_line']['start_x'], v['up_line']['start_y']), 1, (0, 0, 255), 4)
            cv2.circle(show_pred_image, (v['up_line']['end_x'], v['up_line']['end_y']), 1, (0, 0, 255), 4)
            cv2.line(show_pred_image, (v['up_line']['start_x'], v['up_line']['start_y']),
                     (v['up_line']['end_x'], v['up_line']['end_y']),
                     (0, 0, 255), 3)

            cv2.circle(show_pred_image, (v['down_line']['start_x'], v['down_line']['start_y']), 1, (0, 255, 0), 4)
            cv2.circle(show_pred_image, (v['down_line']['end_x'], v['down_line']['end_y']), 1, (0, 255, 0), 4)
            cv2.line(show_pred_image, (v['down_line']['start_x'], v['down_line']['start_y']),
                     (v['down_line']['end_x'], v['down_line']['end_y']),
                     (0, 255, 0), 3)

        show_cobb = ""
        if 'PT' in cobb_dict:
            show_cobb += 'PT (' + cobb_dict['PT']['up_endplate'] + '-' + cobb_dict['PT']['down_endplate'] + ') : ' + str(cobb_dict['PT']['angle']) + '\n'
        if 'MT' in cobb_dict:
            show_cobb += 'MT (' + cobb_dict['MT']['up_endplate'] + '-' + cobb_dict['MT']['down_endplate'] + ') : ' + str(cobb_dict['MT']['angle']) + '\n'
        if 'TL/L' in cobb_dict:
            show_cobb += 'TL/L (' + cobb_dict['TL/L']['up_endplate'] + '-' + cobb_dict['TL/L']['down_endplate'] + ') : ' + str(cobb_dict['TL/L']['angle']) + '\n'

        text_cobb = show_cobb.split("\n")
        for i, text in enumerate(text_cobb[::-1]):
            if len(text) > 1:
                show_pred_image = cv2.putText(show_pred_image, text, (15, show_pred_image.shape[0] - i * 30 - 80),
                                              cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
        cv_show('show', show_pred_image)
        cv_keyboard_run()


def test_DRCobbDet():
    cfg_file = '/home/blake/PycharmProjects/AIS_Algorithm/experiment/app/ais_seg_hrnet_w18_landmark_spinnet_res34_v1.0.0.yml'
    load_cfg_file(cfg_file, logger)
    DRCobbApp = DRCobbDet(cfg_file)
    logger_file = Path(cfg.LOG.DIR).joinpath("DRCobbDet" + time.strftime("--%Y-%m-%d-%H-%M-%S", time.localtime()))
    DRCobbApp.init(logger_file)

    data_root = '/home/blake/data/medical/datasets/vertebral/spine_full_length_photography'
    data_path = Path(data_root)
    image_items = sorted(data_path.joinpath('data', 'all').glob('*.jpg'))

    for image_file in image_items:
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/cs.2019.3.15_1.jpg
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/czh.2018.11.9_1.jpg
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/dwpc2019.1.15_1.jpg
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/hlh2018.7.31_1.jpg ## problem
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/hqh2018.10.29_1.jpg
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/lj.2013.7.18_1.jpg
        #/home/blake/data/medical/datasets/vertebral/spine_full_length_photography/data/all/lj.2014.8.6_2_1.jpg
        print(image_file)
        #image_file = image_file.with_name('hlh2018.8.13_1.jpg')
        image_file = '/home/blake/data/medical/datasets/vertebral/AIS/ais/data/all/lenke5/0019720557/lbend.jpg'
        DRCobbApp.evaluate_case(str(image_file))


if __name__ == '__main__':
    print(__name__)
    test_DRCobbDet()

